import React, {PureComponent} from 'react';
import NavigationFactory from '../../utils/navigationFactory';

import {observer, inject} from 'mobx-react';
import {
  Text,
  View,
  StyleSheet,
  TouchableOpacity,
  DeviceEventEmitter,
  ScrollView,
  Alert,
  findNodeHandle,
  UIManager,
  Dimensions,
  DeviceInfo,
} from 'react-native';
import Search from './search/search';
import windowUtil from '../../utils/windowUtil';
import eventTypes from '../../config/eventTypes';
import searchStorage from '../../storage/searchStorage';
import store from '../../store/hotSearchStore';
import AntDesign from 'react-native-vector-icons/AntDesign';
import arrayUtil from '../../utils/arrayUtil';
import AppConfig from '../../config/appConfig';
import NavigationUtil from '../../utils/navigationUtil';
import MyTabBar from '../../components/MyTabBar/MyTabBar';
import Recommend from '../../components/recommend/Recommend';
import {IsNullObject} from '../../utils/utils';

const TOOLH = DeviceInfo.isIPhoneX_deprecated ? 34 : 0; //状态栏的高度

@NavigationFactory
@inject('HotSearchStore')
@observer
class HotSearchPage extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      value: '',
      history: [],
      renderPage1: true, //true:搜索页 false:结果页
      scrollviewHeight: 0,
      searchType1: AppConfig.TaoBao, // 搜索类型
      searchType2: AppConfig.ZhongHe, // 类型2
      currentSearch2: AppConfig.ZhongHe, //(为searchType2服务)

      curPriceSearch: AppConfig.PriceHeight,
      curSaleSearch: AppConfig.SalesHeight,

      searchData: [], //数据
      pageIndex: 1, //分页申请第几页
      searchScrollviewHeight: 0,
    };

    const {navigation} = this.props;
    navigation.setOptions({
      headerBackTitleVisible: false,
      headerTitle: (props) => (
        <View style={{width: windowUtil.windowWidth() - 120}}>
          <Search
            onSubmit={this.onSubmit}
            onTextChange={this.onTextChange}
            mode={'Input'}
            autoFocus={true}
            {...props}
          />
        </View>
      ),
      headerRight: (props) => (
        <TouchableOpacity
          onPress={() => {
            this.onSubmit(this.state.value);
          }}
          activeOpacity={0.6}>
          <View style={{width: 30, marginRight: 5}}>
            <Text>{'搜索'}</Text>
          </View>
        </TouchableOpacity>
      ),
    });
  }

  onTextChange = (tex) => {
    this.setState({
      value: tex,
    });
  };

  /**
   * 点击取消（暂时废除）
   * */
  onClickCancel = () => {
    DeviceEventEmitter.emit(eventTypes.cancelFocusEvent);
  };

  /**
   * 确定
   * */
  onSubmit = (txt) => {

    if (txt === '') {
      return;
    }

    var temp = this.state.history;
    //存在就删除
    if (temp.includes(txt) === true) {
      temp = arrayUtil.Remove(temp, txt);
    }
    //添加到头
    temp.unshift(txt);
    //限制个数
    if (temp.length > 20) {
      temp.pop();
    }
    //写入缓存
    searchStorage.save(temp).then((e) => {});
    this.getHistoryData();
    //申请网络
    this.setState(
      {
        value: txt,
      },
      () => {
        this.sendSuperSearch(txt);
      },
    );
  };
  /**
   * 发送网格请求获取数据
   * */
  sendSuperSearch(text) {
    //申请网络
    if (IsNullObject(this.refs.RefRecommend) === false) {
      this.refs.RefRecommend.ScrollTop();
    }
    store
      .getSuperSearch(this.state.searchType1, this.state.searchType2, text, 1)
      .then((res) => {
        this.setState({
          renderPage1: false,
          searchData: res.data,
          pageIndex: res.pageIndex,
        });
      });
  }

  /**
   * 清空搜索历史
   * */
  onClearSearch = () => {

    Alert.alert(
      '删除',
      '是否删除历史纪录?',
      [
        {
          text: '确定',
          onPress: () => {
            searchStorage.clear().then((r) => {
              this.setState({
                history: [],
                scrollviewHeight: 0,
              });
            });
          },
        },
        {
          text: '取消',
          style: 'cancel',
          onPress: () => console.log('Cancel Pressed'),
        },
      ],
      {cancelable: false},
    );
  };
  /**
   * 点击历史搜索item
   * */
  onClickHistoryItem = (tex) => {
    // DeviceEventEmitter.emit(eventTypes.setInputText, tex);
    // this.setState({value: tex});
    this.onClickHotItem(tex);
  };

  /**
   * 点击热搜item
   * */
  onClickHotItem = (tex) => {
    DeviceEventEmitter.emit(eventTypes.setInputText, tex);
    this.setState({value: tex});
    this.onSubmit(tex);
  };

  componentDidMount() {
    //获取热搜key
    store.applyKeyWords();
    this.getHistoryData();
  }

  componentDidUpdate() {
    if (this.state.searchScrollviewHeight <= 0) {
      this.getHeight();
    }
  }

  getHistoryData = () => {
    searchStorage.getData().then((data) => {
      this.setState({
        history: data === null ? [] : data,
        scrollviewHeight: data === null ? 0 : 120,
      });
    });
  };

  /**
   * 点击选择淘宝，京东,拼多多
   * */
  onClickChosePage = (value) => {
    this.setState(
      {
        searchType1: value,
      },
      () => {
        this.sendSuperSearch(this.state.value);
      },
    );
  };
  /**
   * 点击选择综合，价格...
   * */
  onClickSecond = (value, title) => {
    console.log(title + ',:' + value);
    let t = value;
    let t1 = this.state.curPriceSearch;
    let t2 = this.state.curSaleSearch;
    if (value === 2) {
      const lastValue = this.state.currentSearch2;
      if (lastValue === value) {
        if (t2 === AppConfig.SalesHeight) {
          t2 = AppConfig.SalesLow;
        } else {
          t2 = AppConfig.SalesHeight;
        }
      }
      t = t2;
    }
    if (value === 3) {
      const lastValue = this.state.currentSearch2;
      if (lastValue === value) {
        if (t1 === AppConfig.PriceHeight) {
          t1 = AppConfig.PriceLow;
        } else {
          t1 = AppConfig.PriceHeight;
        }
      }
      t = t1;
    }
    this.setState(
      {
        searchType2: t,
        currentSearch2: value,
        curPriceSearch: t1,
        curSaleSearch: t2,
      },
      () => {
        this.sendSuperSearch(this.state.value);
      },
    );
  };

  /**
   * 获取滚动高度
   * */
  getHeight = () => {
    if (IsNullObject(this.refs.myTabBarView) === false) {
      const handle = findNodeHandle(this.refs.myTabBarView);
      return new Promise((resolve) => {
        UIManager.measure(handle, (x, y, width, height, pageX, pageY) => {
          if (pageY <= 0) {
            return;
          }
          console.log(x, y, width, height, pageX, pageY);
          const H = Dimensions.get('window').height - pageY - height - TOOLH;
          this.setState({
            searchScrollviewHeight: H,
          });
        });
      });
    }
  };
  /**
   * 更多
   * */
  ToLowerEvent = () => {
    //申请网络
    store
      .getSuperSearch(
        this.state.searchType1,
        this.state.searchType2,
        this.state.value,
        this.state.pageIndex,
      )
      .then((res) => {
        const data = this.state.searchData.concat(res.data);
        this.setState(
          {
            renderPage1: false,
            searchData: data,
            pageIndex: res.pageIndex,
          },
          () => {
            this.refs.RefRecommend.RefData(true);
          },
        );
      });
  };
  render1() {
    const temp = this.state.history;
    return (
      <View>
        <View style={{marginTop: 15}}>
          <Text style={styles.searchText}>热搜</Text>
          <View style={styles.searchContain}>
            {store.keyWords.map((item, key) => {
              return (
                <TouchableOpacity
                  key={key}
                  activeOpacity={0.8}
                  onPress={() => {
                    this.onClickHotItem(item);
                  }}>
                  <View style={styles.searchItem}>
                    <Text style={{fontSize: 16, color: '#666'}}>{item}</Text>
                  </View>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>
        {/*搜索*/}
        <View style={styles.search}>
          <Text style={styles.searchText}>搜索历史</Text>
          <TouchableOpacity
            style={styles.deleteIcon}
            onPress={this.onClearSearch}
            activeOpacity={0.8}>
            <AntDesign name="delete" size={20} color={'#666666'} />
          </TouchableOpacity>
        </View>
        {/*搜索内容*/}
        <ScrollView
          style={{
            marginTop: 10,
            marginBottom: 20,
            width: '100%',
            // height: this.state.scrollviewHeight,
          }}>
          <View ref="searchScrollview" style={styles.searchContain}>
            {temp.map((item, key) => {
              return (
                <TouchableOpacity
                  key={key}
                  activeOpacity={0.8}
                  onPress={() => {
                    this.onClickHistoryItem(item);
                  }}>
                  <View style={styles.searchItem}>
                    <Text style={{fontSize: 16, color: '#666'}}>{item}</Text>
                  </View>
                </TouchableOpacity>
              );
            })}
          </View>
        </ScrollView>
      </View>
    );
  }

  render2() {
    const EmptyView = () => {
      return <View />;
    };
    const navigation1  = this.props.navigation
    return (
      <View style={{flexDirection: 'column'}}>
        <View style={styles.searchResult}>
          {NavigationUtil.CreateMaterialTopTabNavigator({
            root: '淘宝',
            swipeEnabled: true,
            fontSize: 18,
            Screen: [
              {
                name: '淘宝',
                listeners: (t) => {
                  this.onClickChosePage(AppConfig.TaoBao);
                },
                page: EmptyView,
              },
              {
                name: '京东',
                page: EmptyView,
                listeners: (t) => {
                  this.onClickChosePage(AppConfig.JinDong);
                },
              },
              {
                name: '拼多多',
                page: EmptyView,
                listeners: (t) => {
                  this.onClickChosePage(AppConfig.PingDuoDuo);
                },
              },
            ],
          })}
        </View>
        <MyTabBar
          ref={'myTabBarView'}
          backgroundColor={'#efeff0'}
          height={40}
          fontSize={20}
          onClick={(index, title) => {
            this.onClickSecond(index, title);
          }}
          tabList={[
            {title: '综合'},
            {title: '最新', text: 'new'},
            {
              title: '销量',
              text:
                this.state.curSaleSearch === AppConfig.SalesHeight
                  ? '高'
                  : '低',
            },
            {
              title: '价格',
              text:
                this.state.curPriceSearch === AppConfig.PriceHeight
                  ? '高'
                  : '低',
            },
          ]}
        />
        <Recommend
          height={this.state.searchScrollviewHeight}
          ref={'RefRecommend'}
          list={this.state.searchData}
          ToLowerEvent={this.ToLowerEvent}
          navigation={navigation1}
        />
      </View>
    );
  }

  render() {
    let page = null;
    if (this.state.renderPage1 === true) {
      page = this.render1(); //搜索页
    } else {
      page = this.render2(); //结果页面
    }

    return <View style={styles.contain}>{page}</View>;
  }
}

const styles = StyleSheet.create({
  contain: {
    flexDirection: 'column',
  },
  search: {
    marginTop: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  searchText: {
    marginLeft: 15,
    fontSize: 16,
    color: '#121212',
    fontWeight: ('bold', '600'),
  },
  deleteIcon: {
    marginRight: 15,
  },
  searchContain: {
    marginTop: 10,
    marginLeft: 10,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  searchItem: {
    backgroundColor: '#e2e2e2',
    borderRadius: 7,
    margin: 9,
    padding: 2,
  },
  searchResult: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
});

export default HotSearchPage;
